var userLoginId=getParameter('userid');
var userid='';
var username='';
var groupid=getParameter('groupid');



var groupname='';
var isgroupuser='true';
var timerange = 0;  //时间差
var isfirstTime=true;
var password=getParameter('password');
var salt=getParameter('salt');
var token='';

var refreshtime_often=5; //消息发送频繁人员刷新时间(单位秒)
var refreshtime=refreshtime_often*1000;
var refreshtime_unoften=30; //消息发送不频繁人员刷新时间(单位秒)
var isoftentime=60; //消息发送是否频繁界定(单位秒)
var comparetime=new Date();//用于消息发送频繁界定比较时间
var intervalID;//定时器变量
var localmessagers;
var localmessageDate=null;//本地聊天记录最早日期,用于比较时间差
var messageDate=null;//聊天记录最近日期,用于比较时间差

/*附件上传*/
function ajaxFileUpload(inputObj) {
	/*发送消息,此时刷新时间为经常刷新*/
	comparetime=new Date();
	refreshtime=refreshtime_often*1000;

	var sendiddiv='uniqueid'+CurentTime();
	var textfile = '<div class="wjbox">'+
		'<div class="wjbox-top">'+
		'<div class="picbox">' +
		'<span  class="pic"><img src="images/wendang.png" alt=""></span> '+
		'<span class="mingc" id="fszt'+sendiddiv+'">文件发送中..</span>' +
		'</div>'+
		'<div id="progressBarnew"><div id="uploaded'+sendiddiv+'" class="uploaded"></div><p id="info'+sendiddiv+'" class="shuom"></p></div>' +
		'</div></div> ';
	sendinfodiv(textfile,sendiddiv);

	/*window.setTimeout(function(){
		getProgressBar(sendiddiv);
		scrollLast();
	}, 1000);*/

	$.ajaxFileUpload( {
		url : httpurl+'/wechat/springUpload?uniqueid='+sendiddiv,
		secureuri : false,
		fileElementId : inputObj.id,
        type: "post",
        //dataType: "json",
		dataType : 'jsonp',
		//jsonp: "callback",//传递给请求处理程序或页面的，用以获得jsonp回调函数名的参数名(一般默认为:callback)
		//jsonpCallback:"success_jsonpCallback",
		data : {userid:userid, groupid:groupid,token:token, formusername:encodeURIComponent(dialogFromUserName), tousername:encodeURIComponent(dialogToUserName)},
		success : function(data, status) {
			/*clearInterval(intervalID);
			reviceMessage(userid,groupid);
			intervalID = setInterval("reviceMessage(userid,groupid)",refreshtime);*/
			$("#"+sendiddiv).remove();
            var SENDDATE = '2017-1-22';
            var SENDTIME = new Date().getTime() + '';
            var content="<img style='width:48px;height:48px;' src='"+data+" '/>";
            sendAction(userid,content,SENDDATE,SENDTIME);
		},
		error : function(data, status, e) {
			//clearInterval(intervalID);
			//reviceMessage(userid,groupid);
			//intervalID = setInterval("reviceMessage(userid,groupid)",refreshtime);
			//$("#"+sendiddiv).remove();
		}
	})

	return false;
}
/*
 发送聊天信息
 */
function sendMessage(userid,groupid,content,templog){
	$.ajax({
		type: "post",
		url: httpurl+"/wechat/wxSendTextMsg",
		data:{wxuin:userid,to:groupid,content:content,token:token,dialogToUserName:encodeURIComponent(dialogToUserName),dialogFromUserName:encodeURIComponent(dialogFromUserName)},
		dataType: "json",
		timeout: 20000,
		//jsonp: "callback",//传递给请求处理程序或页面的，用以获得jsonp回调函数名的参数名(一般默认为:callback)
		success: function(result){
			if(result['code']==1){
				//保存发送记录
				var messagelogs = [];
				var stringlog = localStorage.getItem(userid+'_'+groupid);
				if(stringlog){
					stringlog = decode64(stringlog);
					messagelogs = JSON.parse(stringlog);
				}
				messagelogs.push(templog);
				localStorage.setItem(userid+'_'+groupid,encode64(JSON.stringify(messagelogs)));
			}else{
				$("#messageList").append('<div class="message"><div class="lsxx"><span class="lsxx-bg">您发送的消息"'+content+'"因服务器问题无法送达,联系管理员</span></div></div>');
			}
		},
		error: function(error){
			$("#messageList").append('<div class="message"><div class="lsxx"><span class="lsxx-bg">您发送的消息"'+content+'"因网络问题无法送达</span></div></div>');
		}
	});
}

/*
 发送请求,获取聊天记录
 */
function reviceMessage(userid,groupid){
	// $.ajax({
	// 	type: "post",
	// 	url: httpurl+"/mobile/staff/webtalk/getReadMessage",
	// 	data:{groupid:groupid,token:token},
	// 	dataType: "jsonp",
	// 	jsonp: "callback",//传递给请求处理程序或页面的，用以获得jsonp回调函数名的参数名(一般默认为:callback)
	// 	success: function(result){
	// 		if(result['code']=='10001'){
	// 			reviceAction(result['infosDetails'],groupid,userid);
	// 		}
	// 	},
	// 	error: function(){
	// 		//alert('fail');
	// 	}
	// });
	/*如果未发送的时间大于isoptentime,则为不经常发送,将刷新时间改为unoften*/
	if((new Date().getTime()-comparetime.getTime())/1000>isoftentime){
		if(refreshtime!=refreshtime_unoften*1000){
			refreshtime=refreshtime_unoften*1000;
			clearInterval(intervalID);
			intervalID = setInterval("reviceMessage(userid,groupid)",refreshtime);
		}
	}else{
		if(refreshtime!=refreshtime_often*1000){
			refreshtime=refreshtime_often*1000;
			clearInterval(intervalID);
			intervalID = setInterval("reviceMessage(userid,groupid)",refreshtime);
		}
	}
}
function reviceAction(data,groupid,userid) {
	var messagelogs = [];
	var stringlog = localStorage.getItem(userid+'_'+groupid);
	if(stringlog){
		stringlog = decode64(stringlog);
		messagelogs = JSON.parse(stringlog);
	}
	var meidascroll = false;
	for(var i=0;i<data.length;i++){
		if (!data[i].MESSAGE) {
		} else {
			var ismediaTemp='N';
			if(data[i].MESSAGE.filename){
				ismediaTemp='Y';
			}
			//限制发送人的文本消息不显示
			if(ismediaTemp=='N'&&data[i].USERID==userid){
				continue;
			}

			var htmlmessage='';
			var templog = {};
			templog['messageid'] = data[i].MESSAGEID;
			templog['userid'] = data[i].USERID;
			templog['username'] = data[i].USERNAME;
			templog['message'] = data[i].MESSAGE;
			templog['senddate'] = data[i].SENDDATE;
			templog['sendtime'] = data[i].SENDTIME;
            templog['headImgUrl'] = data[i].headImgUrl;
			templog['ismedia'] = ismediaTemp;
			messagelogs.push(templog);
			if(messageDate==null){
				messageDate = strToDate(data[i].SENDDATE,data[i].SENDTIME);
				$("#messageList").append("<div class='message'><div class='lsxx'><span class='lsxx-bg'>"+formateTime(data[i].SENDTIME)+"</span></div></div>");
			}else{
				var lastdate = strToDate(data[i].SENDDATE,data[i].SENDTIME);
				if((lastdate.getTime()-messageDate.getTime())/parseInt(1000 * 60)>1){
					$("#messageList").append("<div class='message'><div class='lsxx'><span class='lsxx-bg'>"+formateTime(data[i].SENDTIME)+"</span></div></div>");
				}
				messageDate=lastdate;
			}
			if(data[i].USERID==userid){
				htmlmessage = sendHtml(templog);
			}else{
				htmlmessage = revicehtml(templog);
			}
			$("#messageList").append(htmlmessage);
			if(ismediaTemp=='Y'&&!meidascroll){
				meidascroll = true;
			}
		}
	}
	localStorage.setItem(userid+'_'+groupid,encode64(JSON.stringify(messagelogs)));
	if(myScroll.maxScrollY-myScroll.y>-150){
		scrollLast();
		if(meidascroll){
			window.setTimeout(function(){
				scrollLast();  //图片加载会延迟
			}, 1000);
		}
	}else{
		myScroll.refresh();
	}
}

function sendHtml(data) {
	var bodynew = '';
	if (data.ismedia=='N') {
		if(CheckUrl(data.message)){
			bodynew='<a href="'+data.message+'" id="'+data.messageid+'" target="_blank">'+data.message+'</a>';
		}else{
			bodynew = data.message;
		}
	} else {
		var fileObj = data.message;
		var filetype = fileObj.filetype;
		if (filetype == 'BMP' || filetype == 'PNG' || filetype == 'GIF'
			|| filetype == 'JPG' || filetype == 'JPEG' || filetype == 'bmp'
			|| filetype == 'png' || filetype == 'gif' || filetype == 'jpg'
			|| filetype == 'jpeg') {
			bodynew = '<img class="imgBigger" width="100%" src="' + httpurl+ '/plug-in/downFile.do?wjj='+fileObj.wjj+'&filename='+encodeURIComponent(fileObj.filename) + '&token='+token+'">';
		} else {
			//当附件字数大于6时,进行截取
			var filenamenew = fileObj.filename;
			var filenameindex=fileObj.filename.substring(0,fileObj.filename.lastIndexOf('.'));
			if (/.*[\u4e00-\u9fa5]+.*$/.test(filenameindex)) {
				if (filenameindex.length > 6) {
					filenamenew = filenameindex.substr(0, 6)+ '..' + '.' + filetype;
				}
			} else {
				if (filenameindex.length > 12) {
					filenamenew = filenameindex.substr(0, 12)+ '..' + '.' + filetype;
				}
			}
			bodynew = '<div class="wjbox">'
				+ '<div class="wjbox-top">'
				+ ' <div class="picbox"> <span  class="pic"><img src="images/wendang.png" alt=""></span> '
				+'   <span class="mingc" title="' + fileObj.filename + '">' + filenamenew + '</span></div>'
				+ '    <p class="shuom"> <a  href="javascript:void(0);" onclick="downfile(this,\''
				+ fileObj.wjj + '\',\'' + fileObj.filename
				+ '\');" style="text-decoration:none;">下载</a></p>' +
				'  </div>' + ' </div> ';
		}

	}
	var imgdata=$(".accountUl li.active .avatar img").attr("src");
	var htmlmessage = '<div class="message me">'
		+ ' <div class="message-user">'
		+ ' <span class="message-user-touxiang">'
		+ '<img class="avatar" src="'+imgdata+'">'
		+'</span>'
		+'<span class="message-user-name">'+data.username+'</span>'
		+ '</div>'
		+ '   <div class="messagecontent">'
		+ '       <div class="bubble bubble_primary messageright">'
		+ '            <div class="bubble_cont">'
		+ '                 <div class="plain">'
		+ '                    <pre >' + bodynew + '</pre>'
		+ '                 </div>' + '             </div>'
		+ '         </div>' + '     </div>' + '  </div>';

	return htmlmessage;
}

function revicehtml(data) {// by jinfengling
	var bodynew = '';
	if (data.ismedia=='N') {
		if(CheckUrl(data.message)){
			bodynew='<a href="'+data.message+'" target="_blank">'+recover(data.message)+'</a>';
		}else{
			bodynew = recover(data.message)
		}

	} else {
		var fileObj = data.message;
		var filetype = fileObj.filetype;
		if (filetype == 'BMP' || filetype == 'PNG' || filetype == 'GIF'
			|| filetype == 'JPG' || filetype == 'JPEG' || filetype == 'bmp'
			|| filetype == 'png' || filetype == 'gif' || filetype == 'jpg'
			|| filetype == 'jpeg') {
			bodynew = '<img width="100%" class="imgBigger" src="' + httpurl+ '/plug-in/downFile.do?wjj='+fileObj.wjj+'&filename='+encodeURIComponent(fileObj.filename) + '&token='+token+'">';
		} else {
			//当附件字数大于6时,进行截取
			var filenamenew = fileObj.filename;
			var filenameindex=fileObj.filename.substring(0,fileObj.filename.lastIndexOf('.'));
			if (/.*[\u4e00-\u9fa5]+.*$/.test(filenameindex)) {
				if (filenameindex.length > 6) {
					filenamenew = filenameindex.substr(0, 6)+ '..' + '.' + filetype;
				}
			} else {
				if (filenameindex.length > 12) {
					filenamenew = filenameindex.substr(0, 12)+ '..' + '.' + filetype;
				}
			}
			bodynew = '<div class="wjbox">'
				+ '<div class="wjbox-top">'
				+ ' <div class="picbox"> <span  class="pic"><img src="images/wendang.png" alt=""></span> '
				+'   <span class="mingc" title="' + fileObj.filename + '">' + filenamenew + '</span></div>'
				+ '    <p class="shuom"> <a  href="javascript:void(0);" onclick="downfile(this,\''
				+ fileObj.wjj + '\',\'' + fileObj.filename
				+ '\');" style="text-decoration:none;">下载</a></p>' +
				'  </div>' + ' </div> ';
		}

	}
	var htmlmessage = ' <div class="message">'
		+ ' <div class="message-user">'
		+ ' <span class="message-user-touxiang">'
		+ '<img class="avatar" src="'+data.headImgUrl+'">'
		+'</span>'
		+'<span class="message-user-name">'+data.username+'</span>'
		+ '</div>'
		+ '      <div class="messagecontent">'
		//+ '          <div class="nickname"><span class="time">'+ data.sendtime+ '</span></div>'
		+'           <div class="bubble bubble_default messageleft">'
		+ '               <div class="bubble_cont">'
		+ '                  <div class="plain">'
		+ '                       <pre >' + bodynew + '</pre>'
		+'                    </div>' + '               </div>'
		+ '            </div>' + '         </div>' + '     </div>';
	return htmlmessage;
}

function downfile(athis, wjj, filename) {
	downpath = httpurl+'/plug-in/downFile.do?wjj=' + wjj + '&filename='
		+ encodeURIComponent(encodeURIComponent(filename))+'&token='+token;
	athis.href = downpath;
	// 取消<a>标签原先的onclick事件,使<a>标签点击后通过href跳转(因为无法用js跳转)^-^
	athis.setAttribute("onclick", '');
	// 激发标签点击事件OVER
	athis.click("return false");
}



function sendinfodiv(text ,sendiddiv) {   //附件发送状态
	var htmlmessage = ""
	htmlmessage = '<div class="message me" id="'+sendiddiv+'">'
		+ ' <div class="message-user">'
		+ ' <span class="message-user-touxiang">'
		+ '<img class="avatar" src="images/swhy-xin/user.png" >'
		+'</span>'
		+'<span class="message-user-name">我</span>'
		+ '</div>'
		+ '   <div class="messagecontent">'
		//+ '       <div class="nickname"><span class="time">' + time2 + '</span></div>'
		+ '       <div class="bubble bubble_primary messageright">'
		+ '            <div class="bubble_cont">'
		+ '                 <div class="plain">'
		+ '                    <pre >' + text + '</pre>'
		+ '                 </div>' + '             </div>'
		+ '         </div>' + '     </div>' + '  </div>';

	$("#messageList").append(htmlmessage);
	// alert($("#messageList").scrollHeight);
}

function initialize() {
	// if(userLoginId==''||userLoginId=='undefined'||userLoginId==null){
	// 	$('#progressBar').text('未发现用户,请联系管理员');
	// 	return;
	// }
	// if(groupid==''||groupid=='undefined'||groupid==null){
	// 	$('#progressBar').text('未发现群组,请联系管理员');
	// 	return;
	// }
//	getJBXX();
//	getTimeRange();

	$("#messageList").show();
	//$("#messageList").height(document.body.scrollHeight-96);

}



function HTMLEnCode(str) {
	var s = "";
	if (str.length == 0)
		return "";
	s = str.replace(/&/g, "&gt;");
	s = s.replace(/</g, "&lt;");
	s = s.replace(/>/g, "&gt;");
	s = s.replace(/    /g, "&nbsp;");
	s = s.replace(/\'/g, "'");
	s = s.replace(/\"/g, "&quot;");
	s = s.replace(/\n/g, "<br>");
	return s;
}


//得到当前时间字符串，格式为：YYYY-MM-DD HH:MM:SS
function CurentTime()
{
	var now = new Date();

	var year = now.getFullYear();       //年
	var month = now.getMonth() + 1;     //月
	var day = now.getDate();            //日

	var hh = now.getHours();            //时
	var mm = now.getMinutes();          //分
	var ss=now.getSeconds();			//秒

	var clock = year + "";

	if(month < 10) clock += "0";
	clock += month + "";

	if(day < 10) clock += "0";
	clock += day + "";

	if(hh < 10) clock += "0";
	clock += hh + "";

	if (mm < 10) clock += '0';
	clock += mm+ "";

	if (ss < 10) clock += '0';
	clock += ss;

	return(clock);
}

function getProgressBar(sendiddiv) {
	var startTime;
	var myDate = new Date();
	startTime = myDate.getTime();
	var timestamp = (new Date()).valueOf();
	var bytesReadToShow = 0;
	var contentLengthToShow = 0;
	var bytesReadGtMB = 0;
	var contentLengthGtMB = 0;
	$.ajax({
		type: "post",
		url: httpurl+"/plug-in/getBar.do",
		data:{uniqueid:sendiddiv},
		dataType: "jsonp",
		jsonp: "callback",//传递给请求处理程序或页面的，用以获得jsonp回调函数名的参数名(一般默认为:callback)
		success: function(json){
			var bytesRead = (json.pBytesRead / 1024).toString();
			if (bytesRead > 1024) {
				bytesReadToShow = (bytesRead / 1024).toString();
				bytesReadGtMB = 1;
			}else{
				bytesReadToShow = bytesRead.toString();
			}
			var contentLength = (json.pContentLength / 1024).toString();
			if (contentLength > 1024) {
				contentLengthToShow = (contentLength / 1024).toString();
				contentLengthGtMB = 1;
			}else{
				contentLengthToShow= contentLength.toString();
			}
			bytesReadToShow = bytesReadToShow.substring(0, bytesReadToShow.lastIndexOf(".") + 3);
			contentLengthToShow = contentLengthToShow.substring(0, contentLengthToShow.lastIndexOf(".") + 3);
			if (bytesRead == contentLength&&bytesRead!='0') {
				$("#close").show();
				$("#uploaded"+sendiddiv).css("width", "99.9%");
				$("p#info"+sendiddiv).html("99.9%");
				window.clearTimeout(interval);
				//	$("#subButton").attr("disabled", false);
			} else {
				var pastTimeBySec = (new Date().getTime() - startTime) / 1000;
				var sp = (bytesRead / pastTimeBySec).toString();
				var speed = sp.substring(0, sp.lastIndexOf(".") + 3);
				var percent = "0%";
				if(bytesRead!='0'){
					percent = Math.floor((bytesRead / contentLength) * 100) + "%";
				}
				$("#uploaded"+sendiddiv).css("width", percent);
				$("p#info"+sendiddiv).html(percent+' '+speed+'KB/Sec');
			}
		},
		error: function(){
			//alert('fail');
		}

	});
	var interval = window.setTimeout(function(){
		getProgressBar(sendiddiv)
	}, 2000);
}


function loadlocalmessage(pageindex){
	var messagelogs = [];
	var messageobj={};
	if(pageindex<0) return '';
	var stringlog = localmessagers;
	if(stringlog){
		stringlog = decode64(stringlog);
		messagelogs = JSON.parse(stringlog);
	}
	var start = messagelogs.length;
	var end = 0
	if((messagelogs.length>=(pageindex+1)*10)){//起始页面  28到18
		start = messagelogs.length-(pageindex*10);
		end=messagelogs.length-((pageindex+1)*10);
	}else if(messagelogs.length>pageindex*10&&messagelogs.length<(pageindex+1)*10){
		start = messagelogs.length-(pageindex*10);
		end = 0;
		$("#timeindex").attr("pageindex",-1);
		$("#timeindex").attr("timeindex","isover");
	}else if((messagelogs.length<=(pageindex)*10)){
		$("#timeindex").attr("pageindex",-1);
		$("#timeindex").attr("timeindex","isover");
		return '';
	}
	var htmlmessage = '';
	for(var i=start-1;i>=end;i--){
		if(messagelogs[i].userid==userid){//普通信息
			htmlmessage = sendHtml(messagelogs[i])+htmlmessage;
		}else {//对方发送
			htmlmessage = revicehtml(messagelogs[i])+htmlmessage;
		}
		var dateInfo = '';
		if(new Date().Format('yyyyMMdd')!=messagelogs[i].senddate){
			dateInfo = strToDate(messagelogs[i].senddate,messagelogs[i].sendtime).Format('MM月dd日');
		}
		if(i==end){
			htmlmessage = "<div class='message'><div class='lsxx'><span class='lsxx-bg'>"+dateInfo+formateTime(messagelogs[i].sendtime)+"</span></div></div>"+htmlmessage;
		}else{
			var predate = strToDate(messagelogs[i-1].senddate,messagelogs[i-1].sendtime);
			var thisdate = strToDate(messagelogs[i].senddate,messagelogs[i].sendtime);
			if((thisdate-predate)/parseInt(1000*60)>1){
				htmlmessage = "<div class='message'><div class='lsxx'><span class='lsxx-bg'>"+dateInfo+formateTime(messagelogs[i].sendtime)+"</span></div></div>"+htmlmessage;
			}
		}

	}
	$("#timeindex").attr("pageindex",pageindex+1);
	return htmlmessage;
}
function recover(message){
	var converter = document.createElement("DIV");
	converter.innerHTML = message;
	//var output = converter.innerText;
    var output = converter.innerHTML;
	converter = null;
	message=output;
	return message;
}

function strToDate(date,time) {
	var year = parseInt(date.substring(0,4));
	var month = parseInt(date.substring(4,6))-1;
	var day = parseInt(date.substring(6,8));
	var hour = parseInt(time.substring(0,2));1
	var minute = parseInt(time.substring(2,4));
	var second = parseInt(time.substring(4,6));
	if(time.length==5){
		hour = parseInt(time.substring(0,1));
		minute = parseInt(time.substring(1,3));
		second = parseInt(time.substring(3,5));
	}
	var date = new Date(year, month, day, hour, minute, second);
	return date;
}

/*
 返回标准时间格式15:00:00
 */
function formateTime(time){
	var hour = time.substring(0,2);
	var minute = time.substring(2,4);
	var second = time.substring(4,6);
	if(time.length==5){
		hour = '0'+time.substring(0,1);
		minute = time.substring(1,3);
		second = time.substring(3,5);
	}
	return hour+':'+minute+":"+second;
}

/*
 返回与服务器的时间差
 */
function getTimeRange(){
	$.ajax({
		type: "post",
		url: httpurl+"/mobile/staff/webtalk/getOracleTime",
		data:{},
		dataType: "jsonp",
		jsonp: "callback",//传递给请求处理程序或页面的，用以获得jsonp回调函数名的参数名(一般默认为:callback)
		success: function(result){
			if(result['code']=='10001'){
				var currentdate = result['infosDetails'][0].CURRENTDATE;
				var currenttime = result['infosDetails'][0].CURRENTTIME;
				var oracleDate = Date.parse(strToDate(currentdate,currenttime));
				var date = new Date();
				var localDate = Date.parse(date);
				timerange = oracleDate-localDate;
			}
		},
		error: function(){
		}
	});
}

/*
 获取用户名和群名称
 */
function getJBXX(){
	$.ajax({
		type: "post",
		url: httpurl+"/mobile/staff/webtalk/getJBXX",
		data:{userid:userLoginId,groupid:groupid,password:password,salt:salt},
		dataType: "jsonp",
		jsonp: "callback",//传递给请求处理程序或页面的，用以获得jsonp回调函数名的参数名(一般默认为:callback)
		success: function(result){
			if(result['code']=='10001'){
				userid = result['infosDetails'][0].USERID;
				username = result['infosDetails'][0].USERNAME;
				groupname = result['infosDetails'][0].GROUPNAME;
				isgroupuser = result['infosDetails'][0].ISGROUPUSER;
				token = result['infosDetails'][0].TOKEN;
				if(result['infosDetails'][0].REFRESHTIME_OFTEN&&IsNum(result['infosDetails'][0].REFRESHTIME_OFTEN)){
					refreshtime_often = parseInt(result['infosDetails'][0].REFRESHTIME_OFTEN);
				}
				if(result['infosDetails'][0].REFRESHTIME_UNOFTEN&&IsNum(result['infosDetails'][0].REFRESHTIME_UNOFTEN)){
					refreshtime_unoften = parseInt(result['infosDetails'][0].REFRESHTIME_UNOFTEN);
				}
				if(result['infosDetails'][0].ISOPTENTIME&&IsNum(result['infosDetails'][0].ISOPTENTIME)){
					isoftentime = parseInt(result['infosDetails'][0].ISOPTENTIME);
				}
				refreshtime=refreshtime_often*1000;

				localmessagers = localStorage.getItem(userid+'_'+groupid);//聊天记录
				if($("#timeindex").attr("pageindex")==0){
					pullDownAction();
					setTimeout(function () {
						myScroll.refresh();
						myScroll.scrollTo(0,myScroll.maxScrollY);
					}, 1500);
				}
			}
			if(result['code']=='10003'){
				$('#progressBar').text('用户名或密码错误.....');
				return;
			}
			if(isgroupuser=='false'){
				$('#progressBar').text('你不是该群组的用户.....');
				return;
			}
			if($('#groupUser').html().trim()==''){
				getUserList();
			}
			if(username !=''&&groupname!=''){
				$("#sendto").text(groupname);
				intervalID = setInterval("reviceMessage(userid,groupid)",refreshtime);
				var ajaxbg = $("#background,#progressBar");
				ajaxbg.hide();
			}
		},
		error: function(){
		}
	});
}
function scrollLast(){
	myScroll.refresh();
	myScroll.scrollTo(0,myScroll.maxScrollY);
}

function getUserList(){
	$.ajax({
		type: "post",
		url: httpurl+"/mobile/staff/webtalk/getGroupuser",
		data:{groupid:groupid,token:token},
		dataType: "jsonp",
		jsonp: "callback",//传递给请求处理程序或页面的，用以获得jsonp回调函数名的参数名(一般默认为:callback)
		success: function(result){
			if(result['code']=='10001'){
				$('#groupUser').empty();
				for(var i=0;i<result['infosDetails'].length;i++){
					$('#groupUser').append('<li class="grid user-at" username="'+result['infosDetails'][i].USERNAME+'"><p class="rylb-touxiang"><img class="avatar" src="images/swhy-xin/user.png"></p><p class="col  rylb-text">'+result['infosDetails'][i].USERNAME+'</p></li>');
				}
			}
		},
		error: function(){
		}
	});
}

/**
 * 收信息在左边会话框
 */
function receiveHander(data) {
    var ismediaTemp='N';
    if(data.MESSAGE.filename){
        ismediaTemp='Y';
    }

    var htmlmessage='';
    var templog = {};
    templog['messageid'] = data.MESSAGEID;
    templog['userid'] = data.USERID;
    templog['username'] = data.USERNAME;
    templog['message'] = data.MESSAGE;
    templog['senddate'] = data.SENDDATE;
    templog['sendtime'] = data.SENDTIME;
    templog['headImgUrl'] = data.headImgUrl;
    templog['ismedia'] = ismediaTemp;
   // messagelogs.push(templog);
    if(messageDate==null){
        messageDate = strToDate(data.SENDDATE,data.SENDTIME);
        $("#messageList").append("<div class='message'><div class='lsxx'><span class='lsxx-bg'>"+formateTime(data.SENDTIME)+"</span></div></div>");
    }else{
        var lastdate = strToDate(data.SENDDATE,data.SENDTIME);
        if((lastdate.getTime()-messageDate.getTime())/parseInt(1000 * 60)>1){
            $("#messageList").append("<div class='message'><div class='lsxx'><span class='lsxx-bg'>"+formateTime(data.SENDTIME)+"</span></div></div>");
        }
        //$("#messageList").append("<div class='message'><div class='lsxx'><span class='lsxx-bg'>"+formateTime(data.SENDTIME)+"</span></div></div>");

        messageDate=lastdate;
    }
    if(data.USERID==userid){
        htmlmessage = sendHtml(templog);
    }else{
        htmlmessage = revicehtml(templog);
    }
    $("#messageList").append(htmlmessage);
    if(ismediaTemp=='Y'&&!meidascroll){
        meidascroll = true;
    }
}

/**
 * 发送信息在对话框右边
 */
function sendAction(userid,text,senddate,sendtime) {
    //var text = $('#editArea').html();
    var timestamp = new Date().getTime()+timerange;
    if(sendtime){
        timestamp = sendtime+timerange;
	}
    var oracleDate = new Date();
    oracleDate.setTime(timestamp);
    var senddate = oracleDate.Format("yyyyMMdd");
    var sendtime = oracleDate.Format("hhmmss");
    var templog = {};
    templog['messageid'] = 'messageid'+CurentTime();
    templog['userid'] = userid;
    templog['username'] = userid;
    templog['message'] = text;
    templog['senddate'] = senddate;
    templog['sendtime'] = sendtime;
    templog['ismedia'] = 'N';

    //把原来的uesr 改为wxuid ，groupid 改为现在的tousername
    userid=$("#wxuin").val();
    groupid=$("#toUsers").val();

    if(messageDate==null){
        messageDate = strToDate(senddate,sendtime);
        $("#messageList").append("<div class='message'><div class='lsxx'><span class='lsxx-bg'>"+formateTime(sendtime)+"</span></div></div>");
    }else{
        var lastdate = strToDate(senddate,sendtime);
        if((lastdate.getTime()-messageDate.getTime())/parseInt(1000 * 60)>1){
            $("#messageList").append("<div class='message'><div class='lsxx'><span class='lsxx-bg'>"+formateTime(sendtime)+"</span></div></div>");
        }
        //$("#messageList").append("<div class='message'><div class='lsxx'><span class='lsxx-bg'>"+formateTime(sendtime)+"</span></div></div>");

        messageDate=lastdate;
    }

    var htmlmessage = sendHtml(templog);
    $("#messageList").append(htmlmessage);
}


Date.prototype.format = function(format) {
    var date = {
        "M+": this.getMonth() + 1,
        "d+": this.getDate(),
        "h+": this.getHours(),
        "m+": this.getMinutes(),
        "s+": this.getSeconds(),
        "q+": Math.floor((this.getMonth() + 3) / 3),
        "S+": this.getMilliseconds()
    };
    if (/(y+)/i.test(format)) {
        format = format.replace(RegExp.$1, (this.getFullYear() + '').substr(4 - RegExp.$1.length));
    }
    for (var k in date) {
        if (new RegExp("(" + k + ")").test(format)) {
            format = format.replace(RegExp.$1, RegExp.$1.length == 1
                ? date[k] : ("00" + date[k]).substr(("" + date[k]).length));
        }
    }
    return format;
}
/*console.log(newDate.format('yyyy-MM-dd h:m:s'));*/


/**
* 获取历史记录
 * */
function getHistory() {
	if(isLastPage){
		return;
	}
	var temppageNo=pageNo;
    $.ajax({
        url: base + "/wechat/getMsgByPage",
        data: {
        	formusername:encodeURIComponent(dialogFromUserName),
			tousername:encodeURIComponent(dialogToUserName),
			pageNo:temppageNo,
			pageSize:pageSize
		},
        cache: false,
        dataType: "json",
        timeout: 5000,
        error: function (errorData) {
            //console.log();
           // window.setTimeout(getNewsDatas,3000);
            // jeesnsDialog.errorTips("无法获取所有微信联系人信息！请联系管理员")
        },
        success: function (returnData) {
			/*  var tempdatas="[{'username':'1065619522','total':12,'rows':[" +
			 "{'fromUserName':'@@f47cd0d6ca54e6f8748d2897d05f668d7fdbbc8f72fd84c084d4d6c379fb1909','toUserName':'1065619522','count':10},{'fromUserName':'@@e5a099e8c1456dc011a82dfafcb73301f61d70bb784e56c5c3de6cc4a7d6ebd1','toUserName':'1065619522','count':40}" +
			 "]}]";*/
            var datas = returnData.data;
            if (returnData.page.totalPage == pageNo) {
                isLastPage = true;
            }
			/*  if(dialogFromUserName&&dialogFromUserName!='') {*/
            var data = datas[index];
            var reviceArray=[];
            for (var index in datas) {
                var data = datas[index];
                var content = data.content;
                var desc = '';
                if (content.indexOf("@") != -1) {
                    content = content.substr(content.indexOf(":") + 1);
                    desc = '来自';
                }
                data.MESSAGE = content;
                data.SENDDATE = new Date(data.createtime).format("yyyy-MM-dd");
                data.SENDTIME = data.createtime;
                data.USERNAME = desc + data.formusername;
                data.headImgUrl = data.headImgUrl;
				if(data.formusername==dialogToUserName&&data.tousername==dialogFromUserName){
                  //  receiveHander(data)
                   /* receiveHander(data)*/
               		var content=data.content;
					if(content.indexOf("@")!=-1){
                        content=content.substr(content.indexOf(":")+1);
                    }
                    if(content.indexOf("<br/>")!=-1){
                        content=content.substr(content.indexOf("<br/>")+5);
                    }
					sendAction(dialogToUserName, content, data.SENDDATE,  data.SENDTIME);
				}else{
					if(dialogFromUserName==data.formusername){
						//判断是否是群组
                        var obj = $("#accountHander li[fromToUser='" + data.formusername + "-" + data.tousername + "']");
                        if (obj && obj.length > 0) {
                            data.headImgUrl=obj.find('.img').attr('src')
                        }
					}
                    var timestamp = data.createtime+timerange;
                    var oracleDate = new Date();
                    oracleDate.setTime(timestamp);
                    var senddate = oracleDate.Format("yyyyMMdd");
                    var sendtime = oracleDate.Format("hhmmss");
                    data.SENDDATE =senddate;
                    data.SENDTIME = sendtime;
					receiveHander(data)
                   // datas[index] = data;
				}
            }
            pageNo++;
           // reviceAction(datas, dialogFromUserName, dialogToUserName);

        }
    });
}

//------------------------------iscroll滚动条事件begin------------------------
var myScroll,
	pullDownEl, pullDownOffset,
	pullUpflip;
function pullDownAction () {
	setTimeout(function () {
		myScroll.refresh();
	}, 1000);
	var obj = $("#messageList");
	var result = '';
	var pageindex= $("#timeindex").attr("pageindex");
	var pageindexInt =parseInt(pageindex);
	result = loadlocalmessage(pageindexInt);
    getHistory();
	setTimeout(function () {
		var oldScrollTop = myScroll.maxScrollY;
		obj.prepend(result);
		myScroll.refresh();
		var newScrollTop = myScroll.maxScrollY;
		myScroll.scrollTo(0,newScrollTop-oldScrollTop);

	}, 1000);
}

function loaded() {
	pullDownEl = document.getElementById('pullDown');
	pullDownOffset = pullDownEl.offsetHeight;
	myScroll = new iScroll('yhlbdiv', {
		useTransition: true,
		topOffset: pullDownOffset,
		onRefresh: function () {
			if (pullDownEl.className.match('loading')) {
				pullDownEl.className = '';
				pullDownEl.querySelector('.pullDownLabel').innerHTML = '下拉加载更多...';
			}
		},
		onScrollMove: function () {
			var pageindex= $("#timeindex").attr("pageindex");
			if(pageindex=='-1'){
				pullDownEl.className = '';
				pullDownEl.querySelector('.pullDownLabel').innerHTML = '已经是最后一页.....';
			}else{
				if (this.y > 5 && !pullDownEl.className.match('flip')) {
					pullDownEl.className = 'flip';
					pullDownEl.querySelector('.pullDownLabel').innerHTML = '释放加载...';
					this.minScrollY = 0;
				} else if (this.y < 5 && pullDownEl.className.match('flip')) {
					pullDownEl.className = '';
					pullDownEl.querySelector('.pullDownLabel').innerHTML = '下拉加载更多...';
					this.minScrollY = -pullDownOffset;
				}else if (this.y < (this.maxScrollY - 45)){
					pullUpflip=true;
				}
			}
		},
		onScrollEnd: function () {
			var pageindex= $("#timeindex").attr("pageindex");
			if (pageindex!='-1'&&pullDownEl.className.match('flip')) {
				pullDownEl.className = 'loading';
				pullDownEl.querySelector('.pullDownLabel').innerHTML = '加载中...';
				pullDownAction();
			}
			if(pullUpflip==true){
				myScroll.refresh();
				pullUpflip=false;
			}
		}
	});
}

//document.addEventListener('touchmove', function (e) { e.preventDefault(); }, false);

document.addEventListener('DOMContentLoaded', loaded, false);
//------------------------------iscroll滚动条事件end------------------------

$(function() {
	var _editArea = $('#editArea');
	// 显示隐藏发送按钮
	var _editAreaInterval;

	var qqfacehtml = '';
	for ( var i = 1; i <= 90; i++) {
		qqfacehtml += '<img src="/res/modules/webtalk/css/qqface2/' + i + '.png" class="qqface"/>';
	}
	for ( var i = 91; i <= 132; i++) {
		qqfacehtml += '<img src="/res/modules/webtalk/css/qqface/' + i + '.gif" class="qqface"/>';
	}
	$('#qqfacediv').html(qqfacehtml);



	$('#editArea').focus(function() {
		var display = $('.box_ft_bd').css('display');
		if (display == 'none') {
		} else {
			$('.box_ft_bd').toggleClass('hide');
		}
		var sbottom=$("#operator").css("bottom");
		if(sbottom=="0px"){
			$("#operator").stop(true).animate({bottom:"-192px"});
			$(".box_ft").animate({bottom:"0px"});
			$("#messageList").animate({bottom:"46px"});
			//$("#messageList").height(document.body.scrollHeight-96);
		}
	});

	$('#editArea').blur(function() {

		clearInterval(_editAreaInterval);
	});

	$('#editArea').keyup(function() {
		var text = $('#editArea').text();
		if (text == '' || text == null) {
			$('#btn_sendwj').show();
			$('#btn_send').hide();
		} else {
			$('#btn_sendwj').hide();
			$('#btn_send').show();
		}
		var e=window.event||arguments.callee.caller.arguments[0];
		if(e.keyCode!=8){
			if(text.substring(text.length-1,text.length)=='@'){
				$('#groupUserDiv').animate({height:"100%"});
				$('#header').hide();
			}
		}
	});

	$('#editArea').keydown(function(){
		var e=window.event||arguments.callee.caller.arguments[0];
		if(e.keyCode==13){
			$('#btn_send').click();
			return false;
		}
		//if(e.keyCode==64){    //移动端的@
		//	$('#groupUserDiv').animate({height:"100%"})
		//}
		//if(e.shiftKey&&e.keyCode==50){    //pc端的@
		//	;$('#groupUserDiv').animate({height:"100%"})
		//}
	});


	// 显示隐藏表情栏
	$('.web_wechat_face').click(function() {
		$('.box_ft_bd').toggleClass('hide');

		var sbottom=$("#operator").css("bottom");
		if(sbottom=="0px"){
			$("#operator").stop(true).animate({bottom:"-192px"});
			$(".box_ft").animate({bottom:"0px"});
			$("#messageList").animate({bottom:"46px"});
			//$("#messageList").height(document.body.scrollHeight-96);
		}
	});

	// 切换表情主题
	$('.exp_hd_item').click(function() {
		$('.box_ft_bd').toggleClass('hide');

	});

	// 选中表情
	$('.exp_cont img').click(function() {
		var _this = $(this);
		var html = '<img src="' + _this.attr('src') + '">';// class="' +
		if(_editArea.html()=='<br>'){
			_editArea.empty();
		}
		_editArea.html(_editArea.html() + html);
		// $('#web_wechat_pic').hide();
		$('.box_ft_bd').toggleClass('hide');
		$('#btn_sendwj').hide();
		$('#btn_send').show();
	});



	$('#btn_send').click(function(e) {
		if (e.preventDefault)
			e.preventDefault();
		var text = $('#editArea').html();
		var timestamp = new Date().getTime()+timerange;
		var oracleDate = new Date();
		oracleDate.setTime(timestamp);
		var senddate = oracleDate.Format("yyyyMMdd");
		var sendtime = oracleDate.Format("hhmmss");
		var templog = {};
		templog['messageid'] = 'messageid'+CurentTime();
		templog['userid'] = userid;
		templog['username'] = username;
		templog['message'] = text;
		templog['senddate'] = senddate;
		templog['sendtime'] = sendtime;
		templog['ismedia'] = 'N';

        //把原来的uesr 改为wxuid ，groupid 改为现在的tousername
        userid=$("#wxuin").val();
        groupid=$("#toUsers").val();

		if(messageDate==null){
			messageDate = strToDate(senddate,sendtime);
			$("#messageList").append("<div class='message'><div class='lsxx'><span class='lsxx-bg'>"+formateTime(sendtime)+"</span></div></div>");
		}else{
			var lastdate = strToDate(senddate,sendtime);
			if((lastdate.getTime()-messageDate.getTime())/parseInt(1000 * 60)>1){
				$("#messageList").append("<div class='message'><div class='lsxx'><span class='lsxx-bg'>"+formateTime(sendtime)+"</span></div></div>");
			}
			messageDate=lastdate;
		}

		var htmlmessage = sendHtml(templog);
		$("#messageList").append(htmlmessage);
		scrollLast();
		if(CheckUrl(templog.message)) {
			$.ajax({
				type: "post",
				url: httpurl + "/mobile/staff/webtalk/decodeURL",
				data: {httpurl: encodeURIComponent($('#' + templog['messageid']).attr('href')),token:token},
				dataType: "jsonp",
				jsonp: "callback",//传递给请求处理程序或页面的，用以获得jsonp回调函数名的参数名(一般默认为:callback)
				success: function (result) {
					if (result['code'] == '10001') {
						var title = result['infosDetails'][0].title;
						var description = result['infosDetails'][0].description;
						var imgurl = result['infosDetails'][0].imgurl;
						if (title == null || title == 'undifine' || title == '') {
							title = description;
						}
						if (description == null || description == 'undifine' || description == '') {
							description = $('#' + templog['messageid']).attr('href');
						}
						if (title != null && title != 'undifine' && title != '') {
							$('#' + templog['messageid']).empty();
							text = '<div class="news-box"><img class="news-pic" src="' + imgurl + '"/><span class="news-title">' + title + '</span><div class="news-desp">' + description + '</div></div>';
							$('#' + templog['messageid']).append(text);
							text = '<a href="' + templog['message'] + '" id="' + templog['messageid'] + '" target="_blank">' + text + '</a>'
							templog['message'] = text;
							scrollLast();
						}

					}
					sendMessage(userid, groupid, text, templog);
				},
				error: function () {
					sendMessage(userid, groupid, text, templog);
				}
			});
		}else{
			sendMessage(userid, groupid, text, templog);
		}


		$('#editArea').text('');
		$('#btn_sendwj').show();
		$('#btn_send').hide();

		/*发送消息,此时刷新时间为经常刷新*/
		comparetime=new Date();
	});

	$("#btn_sendwj").click(function(){
		var sbottom=$("#operator").css("bottom");
		if(sbottom=="0px"){
			$("#operator").animate({bottom:"-192px"});
			$(".box_ft").animate({bottom:"0px"});
			//$("#messageList").animate({bottom:"46px"});
			//$("#messageList").height(document.body.scrollHeight-96);
			//$("#messageList").scrollTop($("#messageList").scrollTop()-192);
		}else{
			$("#operator").animate({bottom:"0"});
			$(".box_ft").animate({bottom:"192px"});
			//$("#messageList").animate({bottom:"238px"});
			//$("#messageList").height(document.body.scrollHeight-96-192);
			//$("#messageList").scrollTop($("#messageList").scrollTop()+192);
		}
		var display = $('.box_ft_bd').css('display');
		if (display == 'none') {
		} else {
			$('.box_ft_bd').toggleClass('hide');
		}
	});

	$("#groupUser").on('click','.user-at',function(){
		_editArea.html(_editArea.html() + $(this).attr('username'));
		$(this).addClass("sel").siblings().removeClass("sel");
		$("#userClose").click();

	});

	$("#userClose").click(function(){
		$('#groupUserDiv').animate({height:"0%"});
		$('#header').show();
	});

	$("#yhlbdiv").click(function(){
		var display = $('.box_ft_bd').css('display');
		if (display == 'none') {
		} else {
			$('.box_ft_bd').toggleClass('hide');
		}
		var sbottom=$("#operator").css("bottom");
		if(sbottom=="0px"){
			$("#operator").stop(true).animate({bottom:"-192px"});
			$(".box_ft").animate({bottom:"0px"});
			$("#messageList").animate({bottom:"46px"});
		}
	});

	/*点击图片放大*/
	$("#chatArea").on('click','.imgBigger',function(){
		$("#imgtp").empty();
		$("#imgtp").append($(this).parent().html());
		$("#imgbackground").show();
	});

	$("#imgtp").click(function(){
		$("#imgbackground").hide();
	});

	initialize();
});
